package com.cy.store.service.impl;

import com.cy.store.entity.User;
import com.cy.store.mapper.UserMapper;
import com.cy.store.service.IUserService;
import com.cy.store.service.ex.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

//用户模块业务层实现
@Service
public class IUserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public void reg(User user) {
        //通过user的userName，判断是否注册过
        String username = user.getUsername();
        User result = userMapper.findByUsername(username);
        //如果不为空则抛出异常
        if (result!=null){
            throw new UsernameDuplicateException("用户名已经存在");
        }

        //将密码进行md5加密
        String oldPassword = user.getPassword();
        //获取盐值（随机生成一个盐值）
        String salt = UUID.randomUUID().toString().toUpperCase();
        //将用户的盐值保存起来
        user.setSalt(salt);
        //将密码和盐值进行一个整体进行加密，目的是忽略原有密码的强度，提升了数据的安全性
        String md5Password = getMD5Password(oldPassword,salt);
        //加密之后的密码给到user
        user.setPassword(md5Password);

        //补全数据
        user.setIsDelete(0);
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);


        //为空则可以进行注册
        Integer rows = userMapper.insert(user);
        if (rows!=1){
            throw new InsertException("系统繁忙，请稍后再试");
        }
    }

    @Override
    public User login(String username, String password) {
        //根据传过来的username查询数据库
        User result = userMapper.findByUsername(username);
        // 判断查询结果是否为null
        // 是：抛出UserNotFoundException异常
        if (result==null){
            throw new UserNotFoundException("用户名不存在");
        }
        // 判断查询结果中的isDelete是否为1
        // 是：抛出UserNotFoundException异常
        if (result.getIsDelete()==1){
            throw new UserNotFoundException("用户名不存在");
        }
        // 从查询结果中获取盐值
        String salt = result.getSalt();
        // 调用getMd5Password()方法，将参数password和salt结合起来进行加密
        String newMd5Password = getMD5Password(password, salt);
        String MD5Password = result.getPassword();
        // 判断查询结果中的密码，与以上加密得到的密码是否不一致
        if (!newMd5Password.equals(MD5Password)){
            // 是：抛出PasswordNotMatchException异常
            throw new PasswordNotMatchException("密码错误");
        }
        // 创建新的User对象
        User user = new User();
        // 将查询结果中的uid、username、avatar封装到新的user对象中
        user.setUid(result.getUid());
        user.setUsername(result.getUsername());
        user.setAvatar(result.getAvatar());

        //返回user对象的意义是：为了辅助提交其他页面的数据
        return user;
    }

    @Override
    public void changePassword(Integer uid,String username, String newPassword, String oldPassword) {
        //根据uid查询数据库
        User result = userMapper.findByUid(uid);
        if(result==null||result.getIsDelete() ==1){
            throw new  UserNotFoundException("用户不存在");
        }
        //将原始密码进行MD5加密
        String oldMD5Password = getMD5Password(oldPassword, result.getSalt());
        //将原始密码与数据库中的密码进行比较
        if (!result.getPassword().equals(oldMD5Password)){
            //如果不同则抛出异常
            throw new PasswordNotMatchException("旧密码错误");
        }
        //将新密码进行MD5加密
        String newMD5Password = getMD5Password(newPassword, result.getSalt());
        //将新密码存入数据库中
        Integer rows = userMapper.updatePasswordByUid(uid, newMD5Password, result.getUsername(), new Date());
        if (rows != 1){
            throw new UpdateException("跟新数据产生未知错误");
        }


    }

    @Override
    public User getByUid(Integer uid) {
        User result = userMapper.findByUid(uid);
        if (result == null || result.getIsDelete()==1){
            throw new UserNotFoundException("用户不存在");
        }
        User user = new User();
        user.setUsername(result.getUsername());
        user.setPhone(result.getPhone());
        user.setEmail(result.getEmail());
        user.setGender(result.getGender());

        return user;
    }

    @Override
    public void updateInfo(Integer uid, String username, User user) {
        User result = userMapper.findByUid(uid);
        if (result==null || result.getIsDelete() == 1){
            throw new UserNotFoundException("用户不存在");
        }
        user.setUid(uid);
        user.setModifiedUser(username);
        user.setModifiedTime(new Date());
        Integer rows = userMapper.updateInfoByUid(user);
        if (rows != 1){
            throw new UpdateException("更新出现异常");
        }
    }

    /**
     * 修改用户头像
     * @param uid
     * @param avatar
     * @param username
     */
    @Override
    public void changeAvatar(Integer uid, String avatar, String username) {
        //首先根据uid查询用户是否存在
        User result = userMapper.findByUid(uid);
        if (result==null||result.getIsDelete()==1){
            throw new UserNotFoundException("用户不存在");
        }
        Integer rows = userMapper.updateAvatarByUid(uid, avatar, new Date(),username);
        if (rows!=1){
            throw new UpdateException("修改头像数据时发生异常");
        }
    }


    /**
     * 定义一个md5算法的加密处理
     */
    private String getMD5Password(String password,String salt){
        for (int i = 0;i<3;i++){
            //md5三次加密
            password = DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();
        }
        //返回加密后的密码
        return password;
    }

}
